package com.admin.controller;

import java.io.File;

import org.json.simple.JSONObject;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.JFinal;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

public class FileUploadController extends BaseController {
	
	/**
	 * 上传图片
	 */
	public void index(){
		try {
			UploadFile uf = getFile();
			File file = uf.getFile();
			String path = this.getUploadFile(file);
			if(null == path){
				renderJson(ajax(Status.error,"上传图片路径有误..."));
			}else{
				file.renameTo(new File(path));
				renderJson(ajax(Status.success,path.substring(path.indexOf("upload")).replace("\\","/")));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(),e);
			renderJson(ajax(Status.error,e.getMessage()));
		}
	}
	
	/**
	 * 富文本编辑器上传图片
	 */
	@SuppressWarnings("unchecked")
	public void editorUpload(){
		try {
			UploadFile uf = getFile();
			File file = uf.getFile();
			String path = this.getUploadFile(file);
			JSONObject object = new JSONObject();
			if(null == path){
				object.put("error",1);
				object.put("message","上传错误");
				renderJson(object);
			}else{
				file.renameTo(new File(path));
				object.put("error",0);
				String url = JFinal.me().getContextPath()+"/"+path.substring(path.indexOf("upload")).replace("\\","/");
				object.put("url",url);
				renderJson(object);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(),e);
			renderJson(ajax(Status.error,e.getMessage()));
		}
	}
}
